﻿package net.wangit.adm.user;

import java.util.HashMap;
import java.util.Map;

import net.wangit.MapList;
import net.wangit.context.LocalContext;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.DBFactory;
import net.wangit.support.MapListFactory;
import net.wangit.user.AdminUser;
import net.wangit.view.tree.TreeUtil;


public class OrganizationMapListFactory implements MapListFactory {

	private static final String SQL_ADMINISTRATOR = "select orgid as value, orgname as name from AORG where ";
	private static final String SQL_ORG = "select orgid, orgname,parentid from AORG order by o";

	public OrganizationMapListFactory() {
	}

	public MapList getMapList() {
		try {
			DB db;
			String sql;
			net.wangit.User user = LocalContext.getLocalContext()
					.getActionContext().getVisitor().getUser();
			db = DBFactory.getDB();
			if (user instanceof AdminUser) {
				String administratorId = ((AdminUser) user)
						.getAdministratorId();
				String limit = OrgLimitSqlProvider
						.getAdministratorSql(administratorId);
				sql = (new StringBuilder(
						OrganizationMapListFactory.SQL_ADMINISTRATOR)).append(
						limit).append(" order by ").append("o").toString();
				return db.query(sql);
			} else {
				MapList result;
				result = TreeUtil.getEnumeration(db
						.query(OrganizationMapListFactory.SQL_ORG), "&nbsp;",
						"orgid", "orgname", "parentid");
				if (result == null)
					result = new MapList();
				Map blank = new HashMap();
				blank.put("value", "");
				blank.put("name", "");
				result.insertRow(0, blank);
				return result;
			}
		} catch (Exception e) {
			return null;
		}
	}
}
